import os
from pdfminer.high_level import extract_pages
from pdfminer.layout import LTTextContainer
from io import StringIO

def pdf_to_html(pdf_path, html_path):
    output = StringIO()
    output.write('<html><body>\n')

    # 提取PDF内容并生成HTML
    for page_layout in extract_pages(pdf_path):
        output.write('<div style="page-break-before:always">\n')  # 分页标记
        for element in page_layout:
            if isinstance(element, LTTextContainer):
                text = element.get_text().replace('\n', '<br>')
                output.write(f'<p>{text}</p>\n')
        output.write('</div>\n')

    output.write('</body></html>')

    # 写入HTML文件
    with open(html_path, 'w', encoding='utf-8') as f:
        f.write(output.getvalue())

if __name__ == "__main__":
    pdf_dir = r'/Users/lanyanhua/Downloads/pdf'  # PDF所在目录
    output_dir = os.path.join(pdf_dir, 'HTML')  # 输出目录

    # 创建输出文件夹
    os.makedirs(output_dir, exist_ok=True)

    # 遍历所有PDF文件
    for filename in os.listdir(pdf_dir):
        if filename.lower().endswith('.pdf'):
            pdf_path = os.path.join(pdf_dir, filename)
            html_filename = os.path.splitext(filename)[0] + '.html'
            html_path = os.path.join(output_dir, html_filename)

            try:
                pdf_to_html(pdf_path, html_path)
                print(f'转换成功: {filename} -> {html_filename}')
            except Exception as e:
                print(f'转换失败: {filename} | 错误: {str(e)}')